﻿using B.MESUI.Login.BasicData_UI;
using B.MESUI.Login.BasicData_UI.BasicData;
using B.MESUI.Login.BasicData_UI.BasicData.Select;
using B.MESUI.Login.BasicData_UI.Supplier;
using B.MESUI.Login.EquipmentManagement.DTO;
using B.MESUI.Login.Properties;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.UI;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;
using TextEdit = DevExpress.XtraEditors.TextEdit;

namespace B.MESUI.Login.BasicData_UI.Customer
{
    public partial class GetCustomerForm : XtraForm
    {
        private GetUserControl userControl;
        private TextEdit txtCode, txtName;
        private int pageIndex = 1, pageSize = 10, totalCount = 0;
        public FlowLayoutPanel QueryPanel { get; set; }
        public GetCustomerForm()
        {
            InitializeComponent();
            InitLayout();

            userControl = new GetUserControl { Dock = DockStyle.Fill };
            this.Controls.Add(userControl);

            // 指定需要的查询字段和类型
            var fields = new List<GetUserControl.QueryField>
            {
                new GetUserControl.QueryField { FieldName = "CUSTOMER_CODE", DisplayName = "客户编号", FieldType = GetUserControl.QueryFieldType.TextBox },
                new GetUserControl.QueryField { FieldName = "CUSTOMER_NAME", DisplayName = "客户姓名", FieldType = GetUserControl.QueryFieldType.TextBox }
            };
            userControl.SetQueryFields(fields);

            _ = LoadData();
            // 恢复查询和分页按钮事件绑定
            userControl.btnQuery.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnReset.Click += async (s, e) =>
            {
                var qv = userControl.GetQueryValues();
                foreach (var k in qv.Keys.ToList())
                {
                    if (userControl.QueryControls[k] is DevExpress.XtraEditors.BaseEdit be)
                        be.EditValue = null;
                }
                pageIndex = 1;
                await LoadData();
            };
            userControl.btnPrev.Click += async (s, e) => { if (pageIndex > 1) { pageIndex--; await LoadData(); } };
            userControl.btnNext.Click += async (s, e) => { if (pageIndex < GetTotalPages()) { pageIndex++; await LoadData(); } };
            userControl.btnFirst.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnLast.Click += async (s, e) => { pageIndex = GetTotalPages(); await LoadData(); };
            userControl.btnJump.Click += async (s, e) =>
            {
                int jumpPage;
                if (int.TryParse(userControl.txtJump.Text, out jumpPage))
                {
                    if (jumpPage >= 1 && jumpPage <= GetTotalPages())
                    {
                        pageIndex = jumpPage;
                        await LoadData();
                    }
                }
            };
            userControl.btnAdd.Click += (s, e) =>
            {
                var addForm = new AddCustomerForm();
                addForm.customerEvent += () =>
                {
                    LoadData();
                };
                addForm.ShowDialog();
            };

          
        }

        private int GetTotalPages() => (int)Math.Ceiling((double)totalCount / pageSize);
        /// <summary>
        /// 客户显示
        /// </summary>
        /// <returns></returns>
        private async Task LoadData()
        {
            string url = Settings.Default.BaseUrl_SLY + B.MESUI.Login.BasicData_UI.MethodConst.GetPageCustomer;
            var paramList = new List<string>
            {
                $"PageIndex={pageIndex}",
                $"PageSize={pageSize}"
            };
            var queryValues = userControl.GetQueryValues();
            if (queryValues.ContainsKey("CUSTOMER_CODE") && !string.IsNullOrWhiteSpace(queryValues["CUSTOMER_CODE"]?.ToString()))
                paramList.Add($"CUSTOMER_CODE={queryValues["CUSTOMER_CODE"].ToString().Trim()}");
            if (queryValues.ContainsKey("CUSTOMER_NAME") && !string.IsNullOrWhiteSpace(queryValues["CUSTOMER_NAME"]?.ToString()))
                paramList.Add($"CUSTOMER_NAME={queryValues["CUSTOMER_NAME"].ToString().Trim()}");
            url += "?" + string.Join("&", paramList);
            //添加
            using (HttpClient client = new HttpClient())
            {
                var resp = await client.GetAsync(url);
                string json = await resp.Content.ReadAsStringAsync();
                var jobj = JObject.Parse(json);
                totalCount = jobj["totalCount"]?.Value<int>() ?? 0;
                var pageList = jobj["pageDatas"] as JArray;
                var dataList = new List<CustomerDTO>();
                if (pageList != null)
                {
                    foreach (var item in pageList)
                    {
                        dataList.Add(item.ToObject<CustomerDTO>());
                    }
                }
                // 先绑定数据源
                var gridControl = userControl.MainGrid;
                if (gridControl != null)
                {
                    gridControl.DataSource = dataList;

                    var gridView = gridControl.MainView as GridView;
                    if (gridView != null)
                    {
                        // 添加复选框列
                        if (gridView.Columns["CheckboxColumn"] == null)
                        {
                            // 设置选择模式为多选
                            gridView.OptionsSelection.MultiSelect = true;
                            gridView.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

                            // 添加行点击事件，确保点击行时不会取消其他行的选择
                            gridView.Click += (s, e) =>
                            {
                                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = gridView.CalcHitInfo((e as MouseEventArgs).Location);
                                if (hitInfo.InRow && !(hitInfo.Column != null && hitInfo.Column.FieldName == "CheckboxColumn"))
                                {
                                    // 如果点击的是行而不是复选框列，则切换该行的复选框状态
                                    bool currentValue = Convert.ToBoolean(gridView.GetRowCellValue(hitInfo.RowHandle, "CheckboxColumn"));
                                    gridView.SetRowCellValue(hitInfo.RowHandle, "CheckboxColumn", !currentValue);
                                }
                            };
                        }
                        // 设置表头
                        if (gridView.Columns["CUSTOMER_CODE"] != null)
                            gridView.Columns["CUSTOMER_CODE"].Caption = "客户编号";
                        if (gridView.Columns["CUSTOMER_NAME"] != null)
                            gridView.Columns["CUSTOMER_NAME"].Caption = "客户名称";
                        if (gridView.Columns["CUSTOMER_ABBREVIATION"] != null)
                            gridView.Columns["CUSTOMER_ABBREVIATION"].Caption = "简称";
                        if (gridView.Columns["CUSTOMER_PHONE"] != null)
                            gridView.Columns["CUSTOMER_PHONE"].Caption = "联系电话";
                        if (gridView.Columns["CUSTOMER_ADDRESS"] != null)
                            gridView.Columns["CUSTOMER_ADDRESS"].Caption = "地址";
                        if (gridView.Columns["CREDIT_CODE"] != null)
                            gridView.Columns["CREDIT_CODE"].Caption = "信用代码";
                        if (gridView.Columns["CUSTOMER_NODE"] != null)
                            gridView.Columns["CUSTOMER_NODE"].Caption = "备注";
                        if (gridView.Columns["CREATEDUSERNAME"] != null)
                            gridView.Columns["CREATEDUSERNAME"].Caption = "创建人";
                        if (gridView.Columns["CUSTOMER_NODE"] != null)
                            gridView.Columns["CREATETIME"].Caption = "创建时间";
                        if (gridView.Columns["UPDATEDUSERNAME"] != null)
                            gridView.Columns["UPDATEDUSERNAME"].Caption = "修改人";
                        if (gridView.Columns["UPDATETIME"] != null)
                            gridView.Columns["UPDATETIME"].Caption = "修改时间";

                        AddContactRecordButtonColumn(gridView);
                        AddSalesRecordButtonColumn(gridView);
                    }
                    
                    // 优化中间表格区显示
                    gridControl.Dock = DockStyle.Fill;

                    // 启用滚动功能
                    gridView.OptionsView.ShowVerticalLines = DevExpress.Utils.DefaultBoolean.True;
                    gridView.OptionsView.ShowHorizontalLines = DevExpress.Utils.DefaultBoolean.True;
                    gridView.OptionsView.RowAutoHeight = true;
                    gridView.OptionsScrollAnnotations.ShowErrors = DevExpress.Utils.DefaultBoolean.True;
                    // 允许水平和垂直滚动
                    gridView.OptionsView.EnableAppearanceEvenRow = true;
                    gridView.OptionsView.EnableAppearanceOddRow = true;
                   
                    // 设置滚动条 - 使用最基本的属性
                    gridView.OptionsView.ColumnAutoWidth = false; // 禁用列自动宽度以启用水平滚动
                    gridView.BestFitColumns();
                    // 尝试使用纯反射方式设置滚动条属性
                    try
                    {
                        // 获取OptionsView对象的类型
                        var optionsViewType = gridView.OptionsView.GetType();
                        
                        // 尝试设置水平滚动条
                        var horizontalProperty = optionsViewType.GetProperty("ShowHorizontalScrollBar");
                        if (horizontalProperty != null)
                        {
                            // 获取DefaultBoolean.True的值
                            object trueValue = Enum.Parse(Type.GetType("DevExpress.Utils.DefaultBoolean"), "True");
                            horizontalProperty.SetValue(gridView.OptionsView, trueValue);
                        }
                        
                        // 尝试设置垂直滚动条
                        var verticalProperty = optionsViewType.GetProperty("ShowVerticalScrollBar");
                        if (verticalProperty != null)
                        {
                            // 获取DefaultBoolean.True的值
                            object trueValue = Enum.Parse(Type.GetType("DevExpress.Utils.DefaultBoolean"), "True");
                            verticalProperty.SetValue(gridView.OptionsView, trueValue);
                        }

                        // 较早版本的DevExpress可能使用不同的属性
                        var scrollProps = gridView.GetType().GetProperty("OptionsScroll");
                        if (scrollProps != null)
                        {
                            var optionsScroll = scrollProps.GetValue(gridView);
                            
                            var verticalProp = optionsScroll.GetType().GetProperty("Vertical");
                            if (verticalProp != null)
                                verticalProp.SetValue(optionsScroll, true);
                                
                            var horizontalProp = optionsScroll.GetType().GetProperty("Horizontal");
                            if (horizontalProp != null)
                                horizontalProp.SetValue(optionsScroll, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        // 忽略反射错误，确保程序不会崩溃
                        System.Diagnostics.Debug.WriteLine("设置滚动条时出错: " + ex.Message);
                    }
                    
                    gridView.BestFitColumns(); // 自动适应内容宽度
                    
                    foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView.Columns)
                    {
                        col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; // 表头居中
                        col.AppearanceHeader.Font = new System.Drawing.Font("Tahoma", 10, System.Drawing.FontStyle.Bold); // 表头加粗
                        col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; // 内容居中
                    }
                    // 显示行号
                    gridView.IndicatorWidth = 40;
                    gridView.CustomDrawRowIndicator += (s, e) =>
                    {
                        if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                        {
                            e.Info.DisplayText = (e.RowHandle + 1).ToString();
                        }
                    };
                }
                //调试
                if (userControl.MainGrid != null)
                    userControl.MainGrid.DataSource = dataList;
                userControl.lblPageInfo.Text = $"第{pageIndex}/{(GetTotalPages() == 0 ? 1 : GetTotalPages())}页 共{totalCount}条";

                //修改按钮点击事件
                userControl.btnEdit.Click += (s, e) =>
                {
                    // 获取选中行
                    var gridView = userControl.MainGrid.MainView as GridView;
                    if (gridView != null && gridView.GetSelectedRows().Length > 0)
                    {
                        var selectedRowHandle = gridView.GetSelectedRows()[0];
                        if (selectedRowHandle >= 0)
                        {
                            // 获取选中的客户数据
                            var CustomerDto = gridView.GetRow(selectedRowHandle) as CustomerDTO;
                            if (CustomerDto != null)
                            {
                                // 将 CustomerDTO 转换为 UpdateCustomer
                                var customerDTO = new UpdateCustomer
                                {
                                    ID = CustomerDto.ID,
                                    customeR_NAME = CustomerDto.CUSTOMER_NAME,
                                    customeR_PHONE = CustomerDto.CUSTOMER_PHONE,
                                    crediT_CODE = CustomerDto.CREDIT_CODE,
                                    customeR_CODE = CustomerDto.CUSTOMER_CODE,
                                    customeR_ABBREVIATION = CustomerDto.CUSTOMER_ABBREVIATION,
                                    customeR_ADDRESS = CustomerDto.CUSTOMER_ADDRESS,
                                    customeR_NODE = CustomerDto.CUSTOMER_NODE,
                                };

                                // 创建编辑窗体并传递数据
                                var editForm = new EditCustomerForm(customerDTO);
                                editForm.Customer_Event += () =>
                                {
                                    LoadData();
                                };
                                editForm.ShowDialog();
                            }
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("请先选择要修改的客户记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                };
                //批量删除
                userControl.btnDelete.Click += async (s, e) =>
                {
                    var gridView = userControl.MainGrid.MainView as GridView;
                    if (gridView != null)
                    {
                        // 获取所有选中的行的ID
                        List<string> selectedIds = new List<string>();

                        // 获取选中的行
                        int[] selectedRows = gridView.GetSelectedRows();
                        if (selectedRows != null && selectedRows.Length > 0)
                        {
                            foreach (int rowHandle in selectedRows)
                            {
                                if (rowHandle >= 0)
                                {
                                    var CustomerDto = gridView.GetRow(rowHandle) as CustomerDTO;
                                    if (CustomerDto != null)
                                    {
                                        selectedIds.Add(CustomerDto.ID);
                                    }
                                }
                            }
                        }
                       

                        // 如果没有选中任何行，提示用户
                        if (selectedIds.Count == 0)
                        {
                            XtraMessageBox.Show("请至少选择一条记录进行删除！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        // 确认删除
                        if (XtraMessageBox.Show($"确定要删除选中的 {selectedIds.Count} 条记录吗？", "确认删除",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            try
                            {
                                // 构建请求URL
                                string url1 = $"http://localhost:5198/api/Customer/CustomerDeleteList";

                                // 将ID列表转换为逗号分隔的字符串
                                string idsString = string.Join(",", selectedIds);

                                // 添加查询参数
                                url1 += "?Ids=" + System.Web.HttpUtility.UrlEncode(idsString);

                                // 发送DELETE请求
                                string result = await BaseMethod.MethodsURL("delete", url1);

                                // 解析返回结果
                                var apiResult = JsonConvert.DeserializeObject<dynamic>(result);

                                // 检查返回码
                                if (apiResult != null && apiResult.code.ToString() == "200")
                                {
                                    XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    LoadData(); // 刷新数据
                                }
                                else
                                {
                                    string errorMsg = apiResult?.message?.ToString() ?? "未知错误";
                                    XtraMessageBox.Show($"删除失败：{errorMsg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    LoadData(); // 即使失败也刷新数据，确保UI状态正确
                                }
                            }
                            catch (Exception ex)
                            {
                                XtraMessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                LoadData(); // 发生异常时也刷新数据
                            }
                        }
                    }
                };
                //导出
                userControl.btnExport.Click += (sender, e) =>
                {
                    string url1 = Settings.Default.BaseUrl_SLY + MethodConst.GetExportCustomer;
                    using (HttpClient client1 = new HttpClient())
                    {
                        try
                        {
                            var response = client1.GetAsync(url1).Result;
                            if (response.IsSuccessStatusCode)
                            {
                                var bytes = response.Content.ReadAsByteArrayAsync().Result;
                                using (SaveFileDialog sfd = new SaveFileDialog())
                                {
                                    sfd.Filter = "Excel文件|*.xlsx|所有文件|*.*";
                                    sfd.FileName = "客户信息导出.xlsx";
                                    if (sfd.ShowDialog() == DialogResult.OK)
                                    {
                                        System.IO.File.WriteAllBytes(sfd.FileName, bytes);
                                        MessageBox.Show("导出成功！");
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show("导出失败！");
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("导出异常：" + ex.Message);
                        }
                    }

                };

            }
        }

        /// <summary>
        /// 添加联系记录按钮列
        /// </summary>
        /// <param name="gridView">GridView控件</param>
        private void AddContactRecordButtonColumn(GridView gridView)
        {
            // 彻底移除所有名为ContactRecordColumn的列，防止多次添加
            for (int i = gridView.Columns.Count - 1; i >= 0; i--)
            {
                if (gridView.Columns[i].Name == "ContactRecordColumn")
                {
                    gridView.Columns.RemoveAt(i);
                }
            }
            // 添加“联系记录”按钮列
            RepositoryItemButtonEdit buttonEdit = new RepositoryItemButtonEdit();
            buttonEdit.TextEditStyle = TextEditStyles.HideTextEditor;
            buttonEdit.ButtonsStyle = BorderStyles.UltraFlat;
            buttonEdit.Buttons[0].Kind = ButtonPredefines.Glyph;
            buttonEdit.Buttons[0].Caption = "联系记录";
            buttonEdit.ButtonClick += (s, e) =>
            {
                var view = userControl.MainGrid.MainView as GridView;
                if (view == null) return;
                int rowHandle = view.FocusedRowHandle;
                if (rowHandle < 0) return;
                CustomerDTO customer = view.GetRow(rowHandle) as CustomerDTO;
                if (customer == null) return;
                GetRelationForm relationForm = new GetRelationForm(customer.CUSTOMER_CODE);
                relationForm.Text = $"客户{customer.CUSTOMER_NAME}的联系记录";
                relationForm.ShowDialog();
            };
            userControl.MainGrid.RepositoryItems.Add(buttonEdit);
            GridColumn contactRecordColumn = new GridColumn();
            contactRecordColumn.Caption = "联系记录";
            contactRecordColumn.Name = "ContactRecordColumn";
            contactRecordColumn.FieldName = "ContactRecord";
            contactRecordColumn.VisibleIndex = gridView.Columns.Count; // 添加到最后
            contactRecordColumn.UnboundType = DevExpress.Data.UnboundColumnType.Object;
            contactRecordColumn.ColumnEdit = buttonEdit;
            contactRecordColumn.Width = 80;
            contactRecordColumn.Fixed = FixedStyle.Right; // 固定在最右侧
            gridView.Columns.Add(contactRecordColumn);
        }

        /// <summary>
        /// 添加销售记录按钮列
        /// </summary>
        /// <param name="gridView">GridView控件</param>
        private void AddSalesRecordButtonColumn(GridView gridView)
        {
            // 彻底移除所有名为SalesRecordColumn的列，防止多次添加
            for (int i = gridView.Columns.Count - 1; i >= 0; i--)
            {
                if (gridView.Columns[i].Name == "SalesRecordColumn")
                {
                    gridView.Columns.RemoveAt(i);
                }
            }
            // 添加“销售记录”按钮列
            RepositoryItemButtonEdit buttonEdit = new RepositoryItemButtonEdit();
            buttonEdit.TextEditStyle = TextEditStyles.HideTextEditor;
            buttonEdit.ButtonsStyle = BorderStyles.UltraFlat;
            buttonEdit.Buttons[0].Kind = ButtonPredefines.Glyph;
            buttonEdit.Buttons[0].Caption = "销售记录";
            buttonEdit.ButtonClick += (s, e) =>
            {
                var view = userControl.MainGrid.MainView as GridView;
                if (view == null) return;
                int rowHandle = view.FocusedRowHandle;
                if (rowHandle < 0) return;
                CustomerDTO customer = view.GetRow(rowHandle) as CustomerDTO;
                if (customer == null) return;
                ShowSalesForm salesForm = new ShowSalesForm(customer.CUSTOMER_CODE);
                salesForm.Text = $"客户{customer.CUSTOMER_NAME}的销售记录";
                salesForm.ShowDialog();
            };
            userControl.MainGrid.RepositoryItems.Add(buttonEdit);
            GridColumn salesRecordColumn = new GridColumn();
            salesRecordColumn.Caption = "销售记录";
            salesRecordColumn.Name = "SalesRecordColumn";
            salesRecordColumn.FieldName = "SalesRecord";
            salesRecordColumn.VisibleIndex = gridView.Columns.Count; // 添加到最后
            salesRecordColumn.UnboundType = DevExpress.Data.UnboundColumnType.Object;
            salesRecordColumn.ColumnEdit = buttonEdit;
            salesRecordColumn.Width = 80;
            salesRecordColumn.Fixed = FixedStyle.Right; // 固定在最右侧
            gridView.Columns.Add(salesRecordColumn);
        }

        /// <summary>
        /// 联系记录按钮点击事件处理
        /// </summary>
        private void ButtonEdit_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            // 获取当前行的数据
            GridView view = userControl.MainGrid.MainView as GridView;
            if (view == null) return;
            
            int rowHandle = view.FocusedRowHandle;
            if (rowHandle < 0) return;
            
            // 获取当前行的客户信息
            CustomerDTO customer = view.GetRow(rowHandle) as CustomerDTO;
            if (customer == null) return;
            
            // 打开联系记录表单
            GetRelationForm relationForm = new GetRelationForm(customer.CUSTOMER_CODE);
            relationForm.Text = $"客户{customer.CUSTOMER_NAME}的联系记录";
            relationForm.ShowDialog();
        }
    }
}